﻿using System;
using System.Collections;
using System.Data;
using System.Resources;
using System.Xml;

namespace BdiSyndicatonWarmup
{
    public class BdiXmlRead
    {
        public static DataTable ReadXmlData(string xmlFilePath)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("header");
            dt.Columns.Add("body");
            DataRow dr;
            string temp = string.Empty;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlFilePath);

                XmlNodeList requestNodeList = doc.SelectNodes("/requests/request");
                if (requestNodeList != null)
                {
                    foreach (XmlNode requestNode in requestNodeList)
                    {
                        dr = dt.NewRow();
                        dr[0] = requestNode.Attributes["name"].Value;
                        foreach (XmlNode node in requestNode.ChildNodes)
                        {
                            if (node.Name == "header")
                            {
                                dr[1] = TrimSpace(node.InnerXml);
                            }
                            if (node.Name == "body")
                            {
                                dr[2] = node.InnerXml.Replace("><", ">\r\n<");
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            return dt;
        }

        private static string TrimSpace(string source)
        {
            ArrayList list = new ArrayList();
            source = source.Trim();
            while (source.IndexOf("\r\n") > 0)
            {
                list.Add(source.Substring(0, source.IndexOf("\r\n")).Trim());
                source = source.Substring(source.IndexOf("\r\n")).Trim();
            }
            if (!string.IsNullOrEmpty(source))
            {
                list.Add(source);
            }
            source = string.Empty;
            for (int i = 0; i < list.Count; i++)
            {
                source += list[i] + "\r\n";
            }

            return source.Trim();
        }
    }
}
